package com.higgins.eventtracking.client.health.fundamentals;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.SelectionEvent;
import com.google.gwt.event.logical.shared.SelectionHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.TabBar;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.higgins.eventtracking.client.FinanceTrackingService;
import com.higgins.eventtracking.client.FinanceTrackingServiceAsync;
import com.higgins.eventtracking.client.SecurityAccessDeniedException;
import com.higgins.eventtracking.client.dto.DynamicTypeDTO;
import com.higgins.eventtracking.client.health.action.ActionTab;

public class GoalsTab extends VerticalPanel 		{
	private final FinanceTrackingServiceAsync financeTrackingService = GWT
						.create(FinanceTrackingService.class);
	private boolean firstRun = true;
	private TabPanel tabPanel = new TabPanel();
	private List<SubTab> subTabs = new ArrayList<SubTab>();
	private String dynamicType = null;
	private GoalsSubTabFactory goalsSubTabFactory = new GoalsSubTabFactory();
	
	public GoalsTab(String dynamicType)	{
		this.dynamicType = dynamicType;
		setHeight("35em");
	}
	public void update()	{
		if (firstRun)	
			initialise();
	}
	public void initialise()	{
		populateTabPanel();
		firstRun = false;
	}
	public TabPanel getTabPanel()  {
	    return tabPanel;
	}
	
	public void populateTabPanel()	{
		retrieveFramesOfMind();
	}
	public SelectionHandler<Integer> createSelectionHandler()	{
		SelectionHandler<Integer> selectionHandler = new SelectionHandler<Integer>() {
	        @Override
	        public void onSelection(SelectionEvent<Integer> integerSelectionEvent) {
	        	SubTab selectedSubTab = subTabs.get(integerSelectionEvent.getSelectedItem());
	        	selectedSubTab.update();
	        }
		};
		return selectionHandler;
	}
	

	private void retrieveFramesOfMind()	{
		final List<String> list = new ArrayList<String>();
		try {
			financeTrackingService.retrieveDynamicTypes(dynamicType, new AsyncCallback<List<DynamicTypeDTO>>()  {

				@Override
				public void onFailure(Throwable caught) {

				}

				@Override
				public void onSuccess(List<DynamicTypeDTO> result) {
					tabPanel.clear();
					for (DynamicTypeDTO dto:result)	{
						if (dto.getSubType()==null || dto.getSubType().equals(false))	{
							list.add(dto.getDynamicType());
						}
					}
					addTabs(list, result);
					add(tabPanel);
					if (subTabs.size()>0)	{
						subTabs.get(0).update();
					}
					tabPanel.addSelectionHandler(createSelectionHandler());
				} });
		} catch (IllegalArgumentException e) {

		} catch (SecurityAccessDeniedException e) {

		}	
	}

	private void addTabs(List<String> frameOfMinds, List<DynamicTypeDTO> result)	{
		for (String frameOfMind:frameOfMinds)	{
			SubTab subTab = goalsSubTabFactory.createSubTab(dynamicType, frameOfMind, result);
			subTabs.add(subTab);
			tabPanel.add(subTab, frameOfMind);
		}
		int hour = getHourNow();
		if ((hour >= 9) && (hour <=17) && (dynamicType.equals("TopLevelType")))  {
            SubTab subTab = goalsSubTabFactory.createSubTab(dynamicType, "Job", createJobSubDynamicDTOs(dynamicType));
            subTabs.add(subTab);
            tabPanel.add(subTab, "Job");
		}
		
		tabPanel.selectTab(0);
		if (dynamicType.equals("TopLevelType"))   {
            updateTabTitle(0, "Fuel", true);
            updateTabTitle(1, "Planning", true);
            if ((hour >= 9) && (hour <=17))  {
                updateTabTitle(1, "Job", true);
            }
		}
	}
	
    public void updateTabTitle(Integer index, String title, Boolean alert) {
        TabBar tabBar = tabPanel.getTabBar();
        if (title.equals("Job"))    {
            tabBar.setTabHTML((tabBar.getTabCount()-1), alert?"<div class=\"highlightAlertLabel\" style=\"width: "+ (title.length()*9) +"px;\">" + title + "</div>":title);
        } else {
            tabBar.setTabHTML(index, alert?"<div class=\"highlightGreenLabel\" style=\"width: "+ (title.length()*9) +"px;\">" + title + "</div>":title);
        }
//        if (alert)  {
//            parent.updateTabTitle(this.tabIndex, tabTitle, true);
//        }
    }
	
	private List<DynamicTypeDTO> createJobSubDynamicDTOs(String dynamicType) {
	    List<DynamicTypeDTO> listOfDTOs = new ArrayList<DynamicTypeDTO>();
	    DynamicTypeDTO dto = new DynamicTypeDTO();
	    dto.setDynamicType("Job");
	    dto.setCategory(dynamicType);
	    dto.setSubCategory("Development");
	    dto.setSubType(true);
	    dto.setTimestamp(new Date());
	    listOfDTOs.add(dto);
	    
	    dto = new DynamicTypeDTO();
        dto.setDynamicType("Job");
        dto.setCategory(dynamicType);
        dto.setSubCategory("OnBoarding");
        dto.setSubType(true);
        dto.setTimestamp(new Date());
        listOfDTOs.add(dto);

        dto = new DynamicTypeDTO();
        dto.setDynamicType("Job");
        dto.setCategory(dynamicType);
        dto.setSubCategory("Invoices");
        dto.setSubType(true);
        dto.setTimestamp(new Date());
        listOfDTOs.add(dto);
        
        return listOfDTOs;
	}
	
	private int getHourNow()   {
        String[] dateParts = DateTimeFormat.getFormat( "HH:mm:ss" ).format( new Date() ).split( ":");
        String hourStr = dateParts[0];
        return Integer.valueOf(hourStr);
	}
}
